/*
 * @Descripttion: 
 * @version: 
 * @Author: lixx
 * @Date: 2025-07-04 11:19:18
 * @LastEditors: lixx
 * @LastEditTime: 2025-07-08 17:30:57
 */
import express from "express";
import {SignJWT, importPKCS8, generateKeyPair} from "jose";
import axios from "axios";

const app = express()
const Student = [
    {
        name:'lixx',
        age:22,
        gender:'male'
    }
]

// 配置中间件解析请求体
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 后端解决跨域
app.use((req, res, next) => {
    res.header("Access-Control-Allow-Origin", "*")
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization")
    res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
    next()
})

app.get('/weather',async (req,res) => {
    const response = await axios.get("https://mv7aapwd2m.re.qweatherapi.com/v7/weather/now?location=101010100", {
        headers: {
          'Authorization': 'Bearer eyJhbGciOiJFZERTQSIsImtpZCI6IlRCQjZCUFk2SEsifQ.eyJzdWIiOiIyRDg4RVU4UEVSIiwiaWF0IjoxNzUxODQ5NDE1LCJleHAiOjE3NTE5MzU4MTV9.hBKhYp06gCaQrQfBwusK2_JNckAY8ri-ZrGTwsUutcSx461wWGhz1cOAaM3IVqYB5r3_aj16-mHjFUyvz9PwAQ',
        }
      });
      console.log("response",response.data);
    res.json(response.data)
})
    
app.post("/login",async (req,res) => {
    console.log("req",req.body)
    if(req.body.user === "lixx" && req.body.password === "123456"){
        // 创建一个密钥用于签名（在生产环境中应该使用环境变量或安全存储）
        const secretKey = new TextEncoder().encode("your-secret-key-at-least-32-chars-long");
        
        const token = await new SignJWT({sub:"lixx"})
            .setProtectedHeader({alg:"HS256"})
            .setIssuedAt()
            .setExpirationTime("1h")
            .sign(secretKey);
            
        res.json({token})
    } else {
        res.status(401).json({message: "用户名或密码错误"})
    }
})

app.listen(3333,()=>{
    // console.log('Server is running at http://localhost:3000')
    console.log('Server is running on port 3333');
})
